package com.pactera.base.config;

import com.pactera.base.commons.exception.ServiceException;
import com.pactera.base.commons.vo.RestResponse;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

/**
 * controller 增强
 * 1. 对异常进行捕捉处理
 * 2. 对返回值进行封装
 * @author wangrui
 */

@ControllerAdvice
public class ControllerHandler  {
    /**
     * 全局异常捕捉处理
     *
     * @param ex 异常
     * @return RestResponse<Object>
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public RestResponse<Object> errorHandler(Exception ex) {
        int statusCode;
        StringBuilder msg = new StringBuilder();
        if (ex instanceof HttpRequestMethodNotSupportedException) {
            statusCode = 405;
            msg = new StringBuilder("不支持当前请求方法！请使用 " + Arrays.toString(((HttpRequestMethodNotSupportedException) ex).getSupportedMethods()) + " 方式请求");
        } else if (ex instanceof MissingServletRequestParameterException) {
            statusCode = 400;
            msg = new StringBuilder("缺少请求参数！ [" + ((MissingServletRequestParameterException) ex).getParameterType() + "]" + ((MissingServletRequestParameterException) ex).getParameterName());
        } else if (ex instanceof MethodArgumentNotValidException) {
            statusCode = 400;
            BindingResult bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError error : allErrors) {
                msg.append(error.getDefaultMessage()).append("\n");
            }
        } else if (ex instanceof ServiceException) {
            statusCode = Integer.parseInt(((ServiceException) ex).getErrorCode() == null ? "500" : ((ServiceException) ex).getErrorCode());
            msg = new StringBuilder(((ServiceException) ex).getErrorMessage());
        } else {
            statusCode = 500;
            msg = new StringBuilder("未知错误！" + ex.getMessage() + "!!!");
        }
        RestResponse<Object> respJson = new RestResponse<>();
        respJson.setCode(statusCode);
        respJson.setMsg(msg.toString());
        /*logger.info("发生错误，errorMsg：" + ex.getMessage(), ex);*/
        return respJson;
    }
}